import React, { useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import { Skeleton, Tree } from 'antd';
import { orgTree } from './service';


// 将树形数据格式化成树形结构，字段变更为：title、key、children
const formatTreeData = (data) => {
  return data.map((item) => {
    return {
      title: item.name,
      key: item.id,
      children: item.children ? formatTreeData(item.children) : [],
    };
  });
};

const OrganizationTree = forwardRef(({ req, chooseFirst, onSelect, params = {} }, forwardedRef) => {
  const [dataSource, setDataSource] = useState();
  const [loading, setLoading] = useState(true);
  const [selectedKeys, setSelectedKeys] = useState([]);
  useEffect(() => {
    const fetch = async () => {
      const res = req ? (await req({ ...params })) : (await orgTree({}));
      const data = res.success ? res.data : [];
      setDataSource(data);
      if (chooseFirst) {
        if (data.length > 0) {
          const first = data[0];
          onSelect?.({ name: first.name, id: first.id });
          setSelectedKeys([data[0].id]);
        }

      }
      setLoading(false);
    };
    if (loading) {
      fetch();
    }
  }, [chooseFirst, loading, onSelect, req, params]);

  useImperativeHandle(forwardedRef, () => {
    return {
      reload: () => {
        setLoading(true);
      },
    };
  });

  return (
    <div style={{ margin: 10 }}>
      {loading ? (
        <Skeleton active />
      ) : (
        <Tree
          showLine={{
            showLeafIcon: false,
          }}
          // showIcon={true}
          selectedKeys={selectedKeys}
          defaultExpandAll
          onSelect={(keys, { node }) => {
            if (chooseFirst && keys.length === 0) {
              return;
            }
            onSelect?.(keys.length > 0 ? ({ name: node.title, id: node.key }) : null);
            setSelectedKeys(keys);
          }}
          treeData={formatTreeData(dataSource)}
        />
      )}
    </div>
  );
});

export default OrganizationTree;
